<?php
Class UsersController extends AppController{
	var $name = 'Users';	
	var $paginate = array(
		'limit' => 20,
		'order' => array('User.id' => 'asc')
	);
	var $components = array('Otp', 'Auth', 'RecaptchaPlugin.Recaptcha');
	var $uses = array('User', 'Deal', 'Buyhistory', 'Order', 'Product', 'Billing');
	var $helpers = array('Form', 'RecaptchaPlugin.Recaptcha', 'Thumb'); 
	
	function index() {
	}

	function add_cart($deal_id) {
		$deals = $this->Session->read('Cart');

		if ('' == $deals || !in_array($deal_id, $deals)) {
			if (count($deals) == 10) {
				print_r('You currently have too many items on your cart');
			} else {
				$deals[] = $deal_id;
				$this->Session->write('Cart', $deals);
				print_r('Deal successfully added to your cart');
			}
		} else {
			print_r('You already added this deal to your cart');
		}
		$this->autoRender = false;
	}

	function remove_cart($deal_id) {
		$deals = $this->Session->read('Cart');

		if ('' == $deals || !in_array($deal_id, $deals)) {
			print_r('You have not added this deal to your cart');
		}
		else {
			$key = array_search($deal_id, $deals);
			unset($deals[$key]);
			$this->Session->write('Cart', $deals);
			print_r('Deal successfully removed from your cart');
		}
		$this->autoRender = false;
	}

	function cart() {
		$cart = $this->Session->read('Cart');
		$deals = $this->Deal->find('all', array('conditions' => array(
			'Deal.id' => $cart
		)));
		$this->set(compact('deals'));
	}
	
	function beforeFilter(){
		parent::beforeFilter(); 
		$this->set('curr_user_uid', 0);
		// $this->Auth->deny('admin_demographics','admin_email','admin_psychographics','admin_song');
		//$this->Auth->fields = array('username' => 'emailusername', 'password' => 'password');
		
		// $this->Auth->allow('register', 'index', 'otpresetpassword', 'resetpassword', 'login');
		//$this->Auth->allow('register', 'index', 'otpresetpassword', 'resetpassword', 'login');
		$this->Auth->deny('profile', 'edit_password', 'billing', 'payment');
		$this->set('team_list', $this->Team->find('list', array('fields' => array('Team.name_full'))));	

		$cart = $this->Session->read('Cart');
		if ($cart == '') $cart = array();
		foreach($cart as $key => $value) {
			if ($value == '') unset($cart[$key]);
		}
		$this->Session->write('Cart', $cart);
	}
	/**
	*  The AuthComponent provides the needed functionality
	*  for login, so you can leave this function blank.
	*/
	
	function admin_login() {
		$this->Auth->autoRedirect=false;
		$this->set('view','');
		$user = $this->Auth->user();
		if(!empty($user))
		{
			$this->Session->write('User',$user['User']);
			if($user['User']['role'] == ADMIN) {
				$this->redirect('/admin/users/demographics');
			}
			else{
			//echo('<script>alert("!");</script>');
				$this->redirect($this->Auth->redirect());  
			}
		}else{
	
		}
	}
	
	function admin_logout() {
		$this -> Session -> destroy();
		$this->Session->setFlash("You've successfully logged out.");
        $this->redirect('/');
    }
	
	function login() {
		// $this->last_login();
		// $this->redirect($this->Auth->loginRedirect););
		if($this->Auth->user() && $this->Auth->user('status')!=0){
			$user = $this->Auth->user();
			$this->Session->setFlash('Welcome to dealcruncher, ' .$user['User']['name']);
			$this->redirect($this->referer());
		}
		else {
			$this->Session->setFlash('Invalid email or password. Please try again');
			$this->redirect('/');
		}
	}
	function logout() {
		$this->facebook->destroySession();
		$this->Session->destroy();
		$this->Auth->logout();
		// debug($this->Session->read('Facebook.logoutUrl'));
		// $this->redirect($this->Session->read('Facebook.logoutUrl'));
		// $this->redirect('http://google.com');
		$this->redirect('/');
	}
	
	function email_validate($email) {
		$reg = "/^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/";
		if(preg_match($reg, $email) > 0) {
			return true;
		}
		else
		{
			return false;
		}
	}
	
	function register()
	{
		if(!empty($this->data))
		{
			if ($this->data['User']['password'] == $this->Auth->password($this->data['User']['password_confirm']))
			{
				if(!$this->User->findByUsername($this->data['User']['username']))
				{
					$user = $this->data;
					$now = microtime(true);
					$ttl =$now + 48*3600; // the verification is good for the next two days

					// create the OTP - TTL = time to live
					$otp = $this->Otp->createOTP(array('user'=>$user["User"]["username"],'password'=>$user["User"]["password"],'ttl'=> $ttl) );

					$link = CURRENT_PATH . $this->webroot . 'users/otpregister/'.$user["User"]["username"].'/'.$user["User"]["password"].'/'.$ttl.'/'.$otp;
					 // body construction
					$body = <<<BODY
					Hi guest,<br><br>

					You have registerred an account with Dealcruncher.com. To complete your request, please follow this link:<br><br>

					{$link}<br><br>

					Thanks,<br>
					Dealcruncher Team<br>
BODY;
					// send mail using phpmailer
					App::import( 'Vendor', 'PHPMailer', array( 'file' => 'PHPMailer'.DS.'class.phpmailer.php' ) );

					$mail = new PHPMailer();

					$mail->IsSMTP();  // telling the class to use SMTP
					$mail->IsHtml(true);  // telling the class to use SMTP
					$mail->Host     = "ssl://smtp.gmail.com:465"; // SMTP server
					$mail->SMTPAuth = TRUE;
					$mail->Username = "noreply.smartplanner@gmail.com";  // Change this to your gmail adress
					$mail->Password = "smartplanner";
					$mail->From     = "nguyen.lamphuc@gmail.com"; 
					
					$mail->FromName = "Dealcruncher Admin";
					
					// $mail->AddAddress($username);
					$mail->AddAddress($this->data['User']['username']);
					$mail->Subject  = "You have registerred an account with Dealcruncher.com";
					$mail->Body     = $body;

					if(!$mail->Send()) {
						$response->message = 'Message was not sent.' . $mail->ErrorInfo;
						$response->status = "fail";
						exit;
					} 
					else 
					{
						$response->message = 'An email has been sent your mailbox, follow instructions there to activate your account!';
						$response->status = "success";
						echo json_encode($response);
						exit;
					}
				}
				else{
					$this->data['User']['password'] = '';
					$this->data['User']['password_confirm'] = '';
					$response->status = "fail";
					$response->message = 'This email is already in use, please try another!';
					echo json_encode($response);
					exit;
				}
			}
			else
			{
				$this->data['User']['password'] = '';
				$this->data['User']['password_confirm'] = '';
				$response->status = "fail";
				$response->message = 'Typed passwords did not match';
				echo json_encode($response);
				exit;
			}
		}
	}

	function otpregister($username,$password,$ttl,$otp) {
		$user["User"]["username"] = $username;
		$user["User"]["password"] = $password;
		if(!$this->User->findByUsername($username))
		{
			$now = microtime(true);
			// check expiration date. the experation date should be greater them now.
			if($now <  $ttl){
				// validate OTP
				if($this->Otp->authenticateOTP($otp, array('user'=>$username,'password'=>$password,'ttl'=> $ttl)) ){
					$this->User->create();
					if($this->User->save($user, array('validate' => false)))
					{
						$this->User->member_count_update(true);
						
						if($this->Auth->login($user))
						{
							$this->User->saveField('lastlogin', date('Y-m-d H:i:s')); //updating last_login field.
						}
						$this->Session->setFlash('Welcome to dealcruncher!');
					}
					else
					{
						$this->Session->setFlash('Cannot connect to database. Please try again later!');
					}
				}
				else{
					$this->Session->setFlash("Invalid request. Please contact the website administration.");
					//$this->redirect(array('action' => 'message'));

				}
			}
			else{
				$this->Session->setFlash("Your invitation has expired. Please contact the website administration.");
				//$this->redirect(array('action' => 'message'));
			}
		}
		$this->redirect('/');
		//TODO: handle invalid request with no parameters
	}
	
	function view($id = null) {
		if ($id == null) {
			$id = $this->Session->read('Auth.User.id');
		}
		$this->User->recursive = 2;
		$user_data = $this->User->findById($id);
		$this->User->recursive = 1;
		if ($user_data == null) {
			$this->Session->setFlash('User data not found.');
			$this->redirect('/');
		}

		$cart = $this->Session->read('Cart');
		if ('' == $cart) $cart = array();
		foreach($user_data['Deal'] as $key => $deal) {
			$user_data['Deal'][$key]['InCart'] = in_array($deal['id'], $cart);
		}
		$can_edit = $id == $this->Session->read('Auth.User.id');

		if ($can_edit) {
			$orders = $this->Order->find('all', array(
				'conditions' => array('user_id' => $id, 'status' => '1'),
			));
		} else $orders = array();

		$this->set(compact('user_data', 'can_edit', 'orders'));
	}
	
	function profile($id = null)
	{
		$user_id = $this->Session->read('Auth.User.id');
		$this->set('user_id', $user_id);
		if(empty($this->data))
		{
			$this->data = $this->User->findById($this->Session->read('Auth.User.id'));
		}
		else
		{
			$this->User->id = $this->Session->read('Auth.User.id');
			$user = $this->User->read();
			$error = '';
			
			
			if (isset($this->data['User']['image_form']) && $this->data['User']['image_form']['name']) 
			{	
				$file_info = pathinfo($this->data['User']['image_form']['name']);	
				$tmpFile = $this->data['User']['image_form']['tmp_name'];
				$ext = $file_info['extension'];
				if(($ext != 'jpg') && ($ext != 'png') && ($ext != 'gif'))
				{
					$error = 'File type JPG,PNG or GIF only';
				}
				
				if($this->data['User']['image_form']['size'] > 512000)
				{
				
					$error = 'Maximum of 500KB';
				}
				
				if($error == null)
				{
					if (isset($tmpFile) && $tmpFile) 
					{
						// check for directory for image upload
						$folder = CURR_FILE_PATH . 'avatar/';
						$file_info['filename'] = md5($file_info['filename']);
						if (!file_exists($folder)) {
							mkdir($folder, 0777);
						}
						
						// Delete the old picture when the user upload a new one
						if(isset($user['User']['avatar']) && $user['User']['avatar'])
						{
							$myOldFile = CURR_FILE_PATH . $user['User']['avatar'];
							if(file_exists($myOldFile))
							{
								$myOldFile1 = new File(CURR_FILE_PATH . $user['User']['avatar']);
								if($myOldFile1->delete()) // Cannot do $myOldFile->delete();
								{
									//do sth
								}
								else
								{
									//do sth
								}
							}
						}
						
						// Copy the file from temp folder to the wanted folder
						$myFile = $folder . $file_info['filename']. '.' . $ext;
						
						if(move_uploaded_file($tmpFile, $myFile))
						{
							$this->data['User']['avatar'] = 'avatar/'.$file_info['filename']. '.' . $ext;
						}
					}
				}
			}
			
			if($error == null)
			{
				if($this->User->save($this->data, /* important */array('validate' => false)))
				{
					$this->Session->setFlash('Your profile has been saved successfully');
					/* Cannot do $this->data = $user because $user was read before save so the information is not updated */
					$this->User->id = $id;
					$this->data = $this->User->read();
					
					$this->Session->write("Auth.User", $this->data['User']);
					$this->redirect('/users/view/'.$user_id);
				}
				else
				{
					$this->Session->setFlash('Unable to update your profile, please try again.');
				}
			}
			else
			{
				$this->data = $this->User->read();
				$this->data['User']['error'] = $error;
			}
		}
	}
	
	function edit_password($id = null)
	{
		$user_id = $this->Session->read('Auth.User.id');
		$this->set(compact('user_id'));
		if(!empty($this->data))
		{
			$this->User->id = $this->Session->read('Auth.User.id');
			$user = $this->User->read();
			if($this->Auth->password($this->data['User']['old_password']) == $user['User']['password'])
			{
				if($this->data['User']['password'] == $this->data['User']['password_confirm'])
				{
					// To validate field password only
					$this->User->set($this->data);
					if($this->User->validates(array('fieldList' => array('password_confirm'))))
					{
						if($this->User->saveField('password', $this->Auth->password($this->data['User']['password'])))
						{
							$this->Session->setFlash(__('Your password has been changed.', true));
							$this->redirect('/users/view');
						}
						else
						{
							$this->Session->setFlash('Unable to change your password, please try again.');
						}
					}
				}
				else
				{
					$this->Session->setFlash('Typed passwords did not match!');
				}
			}
			else
			{
				$this->Session->setFlash('Your old password is not correct, please try again!');
			}
		}
	}
	
	function username($user_name)
	{
		$available = $this->User->findByUsername($user_name);
		//	debug($available);
		if(empty($available))
		{
			$json_return['available'] = true;
		}
		else
		{
			$json_return['available'] = false;
		}
		
		$this->autoRender = false;
		print_r(json_encode($json_return));
	}
	
	
	
	
	function forget_password() {
        if (!empty($this->data)) {
            $username = $this->data["User"]["username"];			
            $user = $this->User->findByUsername($username);
			$id = $user["User"]["id"];
			if($user){
				// TODO validate that username is in an EMAIL format

				// create a random password)
				// $randomPass = $this->Auth->password($this->generatePassword());
				// $this->User->saveField('password', $randomPass);

				// setup the TIME TO LIVE (valid until date) for the next two days
				$now = microtime(true);
				$ttl =$now + 48*3600; // the invitation is good for the next two days

				// create the OTP - TTL = time to live
				$otp = $this->Otp->createOTP(array('user'=>$username,'password'=>$user["User"]["password"],'ttl'=> $ttl) );

				$link = CURRENT_PATH . $this->webroot . 'users/otpresetpassword/'.$username.'/'.$ttl.'/'.$otp;
				 // body construction
				$body = <<<BODY
				Hi {$user["User"]["name"]},<br><br>

				You recently asked to reset your 40UP password. To complete your request, please follow this link:<br><br>

				{$link}<br><br>

				Thanks,<br>
				40UP Team<br>
BODY;
				// send mail using phpmailer
				App::import( 'Vendor', 'PHPMailer', array( 'file' => 'PHPMailer'.DS.'class.phpmailer.php' ) );

				$mail = new PHPMailer();

				$mail->IsSMTP();  // telling the class to use SMTP
				$mail->IsHtml(true);  // telling the class to use SMTP
				// $mail->Host     = "localhost"; // SMTP server
				// $mail->SMTPAuth = FALSE;
				// for localhost only
				$mail->Host     = "ssl://smtp.gmail.com:465"; // SMTP server
				$mail->SMTPAuth = TRUE;
				$mail->Username = "email";  // Change this to your gmail adress
				$mail->Password = "password";  // Change this to your gmail password
				$mail->From     = "nguyen.lamphuc@gmail.com"; 
				
				// $mail->From     = "admin@40up.sg";
				$mail->FromName = "40UP Admin";
				
				$mail->AddAddress($username);
				$mail->Subject  = "You requested a new 40UP password";
				$mail->Body     = $body;

				if(!$mail->Send()) {
					$this->Session->setFlash('Message was not sent.');
					echo 'Mailer error: ' . $mail->ErrorInfo;
				} 
				else 
				{
					$this->Session->setFlash('An email has been sent your mailbox, follow instructions there to activate reset your password!');
				}
			}
			else
			{
				$this->Session->setFlash("This user is not in the system, please try another email");		  
			}          
        }
    }

    // after clicking the link in the registration email the user will be sent here
	function otpresetpassword($username,$ttl,$otp) {
		if($username){
			$user = $this->User->FindByUsername($username);
			if($user){
				$password = $user["User"]["password"];

				$now = microtime(true);
				// check expiration date. the experation date should be greater them now.
				if($now <  $ttl){
					// validate OTP
					if($this->Otp->authenticateOTP($otp, array('user'=>$username,'password'=>$password,'ttl'=> $ttl)) ){
						if($this->data){
							// set the password
							debug($this->data);
							if($this->data['User']['password'] == $this->data['User']['password_confirm'])
							{
								$this->User->set($this->data);
								if($this->User->validates(array('fieldList' => array('password_confirm'))))
								{
									$password = $this->data["User"]["password"];
									$this->User->id =  $user["User"]["id"];
									
									$this->User->saveField('password',   $this->Auth->password($password));
									$this->Session->setFlash( 'Congratulations! Your password has been changed');
									//$this->redirect(array('action' => 'success'));
									$this->redirect('/');
								}
							}
							else
							{
								$this->Session->setFlash('Typed passwords did not match');
							}
						}
						//$this->Session->setFlash("Password resetted, Please try to login");
						//$this->redirect(array('controller' => 'User' , 'action' => 'login'));

					}else{
						$this->Session->setFlash("Invalid request. Please contact the website administration.");
						//$this->redirect(array('action' => 'message'));

					}
				}else{
					$this->Session->setFlash("Your invitation has expired. Please contact the website administration.");
					//$this->redirect(array('action' => 'message'));
				}
			}
		}
		//TODO: handle invalid request with no parameters
	}

    function generatePassword($length=6, $strength=0){
		$vowels = 'aeuy';
		$consonants = 'bdghjmnpqrstvz';
		if ($strength & 1) {
			$consonants .= 'BDGHJLMNPQRSTVWXZ';
		}
		if ($strength & 2) {
			$vowels .= "AEUY";
		}
		if ($strength & 4) {
			$consonants .= '23456789';
		}
		if ($strength & 8) {
			$consonants .= '@#$%';
		}

		$password = '';
		$alt = time() % 2;
		for ($i = 0; $i < $length; $i++) {
			if ($alt == 1) {
				$password .= $consonants[(rand() % strlen($consonants))];
				$alt = 0;
			} else {
				$password .= $vowels[(rand() % strlen($vowels))];
				$alt = 1;
			}
		}
		return $password;
	}
	
	function admin_demographics(){
		$user=$this->Auth->user();
		if(!$user||$user['User']['role']!=0){
			$this->redirect(array('controller'=>'users','action'=>'admin_login'));
		}
		$all_user = $this->User->find('list');
		$this->set('all_user', $all_user);

		$fromDate = '2012-09-20';
	
		if(isset($this->params['url']['from']) && isset($this->params['url']['to'])){
			$fromDate = $this->params['url']['from'];
			$toDate = $this->params['url']['to'];
		}
		else{//show current month by default
			$curr_time = time();
			//$fromDate =date('Y-m-d', strtotime('-30 day', $curr_time));
			$toDate = date('Y-m-d', $curr_time);
		}
		
		$this->data['Stats']['from'] = $fromDate;
		$this->data['Stats']['to'] = $toDate;
		$this->set('fromDate', $fromDate);
		$this->set('toDate', $toDate);
				
		$categories = $this->Product->find('list');
		$detail='id, description';
		$topNum = 20; 
		$filter="CASE WHEN (product_id = 0) THEN 'others' ";
		foreach($categories as $key => $category){
			$filter .= "WHEN (product_id = $key) THEN '$category' ";
		}
		$filter .= " END";
		
		// Deal analysis
		$analysis='name';
		$deal_tops=array(); //for store the top list of user(popup usage)
		$deal_p =array(); //percentage of each group
        $this->demographic_deal($analysis,$categories, $detail, $filter, $fromDate, $toDate,$topNum,$deal_tops,$deal_p);
		$this->set('deals',$deal_p);
		$this->set('deal_tops',$deal_tops);
	
		// Sales analysis
		$analysis2='name';
		$detail2 = 'id, deal_id, user_id';
		$deal_tops2=array(); //for store the top list of user(popup usage)
		$deal_p2 =array(); //percentage of each group
        $this->demographic_sale($analysis2,$categories, $detail2, $filter, $fromDate, $toDate, $topNum, $sale_tops, $sale_p);
		$this->set('sales',$sale_p);
		$this->set('sale_tops',$sale_tops);
		
		// User demographics
		$focus='users';
		$record=array();
		$this->newRecord($focus, $fromDate, $toDate, &$record);
		$this->set('users',$record);
	}
	
	
	function demographic_sale($analysis,$category,$detail, $filter, $fromDate, $toDate,$topNum,&$tops,&$group_p){
		$sql="SELECT COUNT(1) AS count, ".$analysis."
					FROM
					(SELECT id,
					(".$filter.") AS ".$analysis."
					FROM buyhistories 
					WHERE DATE(created) BETWEEN '".$fromDate."' AND '".$toDate."') Category
					GROUP BY ".$analysis."";
		$result = $this->Buyhistory->query($sql);
		
		//percentage:	
		$conditions = array ('date(Buyhistory.created) BETWEEN ? and ?' => array($fromDate, $toDate));

		for($i=0; $i<count($result);$i++){
			$result[$i]['percentage'] =  $result[$i][0]['count']/$this->Buyhistory->find('count',array('conditions'=>$conditions));
			if ($result[$i]['Category']['name'] == ''){
				$result[$i]['Category']['name'] = 'others';
			}
			else{
				$category_flip = array_flip($category);
				$result[$i]['Category']['id'] = $category_flip[$result[$i]['Category']['name']];
			}

			if (strlen($result[$i]['Category']['name']) > 30)
				$result[$i]['Category']['name'] = substr($result[$i]['Category']['name'], 0, 30) . '...';
		}
		
		//$this->set('gender',$gender);
		$group_p = $result;
		if($category!=null){
			//get detail:
			foreach($category as $key => $value){
				$sql = "select Detail.id, Detail.user_id, deals.user_id from (SELECT ".$detail.",
						(".$filter.") AS ".$analysis."
						FROM buyhistories 
						where DATE(created) BETWEEN '".$fromDate."' AND '".$toDate."') Detail LEFT JOIN deals ON Detail.deal_id = deals.id WHERE Detail.".$analysis." = '".$value."' LIMIT ".$topNum." ";
				
				$results = $this->Buyhistory->query($sql);
				@$tops[$key]=$results;
			}
		}
	
	}//end of demographic function
	
	function demographic_deal($analysis,$category,$detail, $filter, $fromDate, $toDate,$topNum,&$tops,&$group_p){
		$sql="SELECT COUNT(1) AS count, ".$analysis."
					FROM
					(SELECT id,
					(".$filter.") AS ".$analysis."
					FROM deals 
					WHERE DATE(created) BETWEEN '".$fromDate."' AND '".$toDate."') Category
					GROUP BY ".$analysis.
					" LIMIT 10";
		$result = $this->Deal->query($sql);
		
		//percentage:	
		$conditions = array ('date(Deal.created) BETWEEN ? and ?' => array($fromDate, $toDate));

		for($i=0; $i<count($result);$i++){
			$result[$i]['percentage'] =  $result[$i][0]['count']/$this->Deal->find('count',array('conditions'=>$conditions));
			if ($result[$i]['Category']['name'] == ''){
				$result[$i]['Category']['name'] = 'others';
			}
			else{
				$category_flip = array_flip($category);
				$result[$i]['Category']['id'] = $category_flip[$result[$i]['Category']['name']];
			}

			if (strlen($result[$i]['Category']['name']) > 20)
				$result[$i]['Category']['name'] = substr($result[$i]['Category']['name'], 0, 20) . '...';
		}
		
		//$this->set('gender',$gender);
		$group_p = $result;
		if($category!=null){
			//get detail:
			foreach($category as $key => $value){
				$sql = "select * from (SELECT ".$detail.",
						(".$filter.") AS ".$analysis."
						FROM deals 
						where DATE(created) BETWEEN '".$fromDate."' AND '".$toDate."') Detail WHERE Detail.".$analysis." = '".$value."' LIMIT ".$topNum." ";
				
				$results = $this->Deal->query($sql);
				@$tops[$key]=$results;
			}
		}
		// debug($tops);
		// debug($group_p);
	
	}//end of demographic function
	
	function newRecord($focus, $fromDate, $toDate, &$record){
	//--------new user register in a date range---------------
		$sql="SELECT DATE(created) AS date, COUNT(1) AS count
					FROM ".$focus."
					WHERE DATE(created) BETWEEN '".$fromDate."' AND '".$toDate."'
					GROUP BY date
					ORDER BY date ASC";
		$result = $this->User->query($sql);
		
		//count total date regardless of 0 result, initailize the array:
		$day_total = abs(strtotime($toDate) - strtotime($fromDate))/(60*60*24)+1;	
	
		
		for($i=0;$i<$day_total;$i++){
			$count[$i]=0;
			$add ='+'.$i.' day';
			$date[$i]=date('Y-m-d', strtotime($add,strtotime($fromDate)));
		}
	
		foreach($result as $value){
			$date_index = abs(strtotime($value[0]['date'])-strtotime($fromDate))/(60*60*24);
			$count[$date_index] = $value[0]['count'];
			
		}
		for($i=0;$i<$day_total;$i++){
			@$record[$date[$i]]=$count[$i];
		}
	
	}
	
	function admin_member(){
		$user=$this->Auth->user();
		if(!$user||$user['User']['role']!=ADMIN){
			$this->redirect(array('controller'=>'users','action'=>'admin_login'));
		}
	
		$users = $this->paginate('User', array('User.role <>' => ADMIN));
		$this->set('users',$users);
		if(!empty($users))
			$this->set('dataempty',false);
		else
			$this->set('dataempty',true);
	}
	
	function admin_delete($id=null){
		if(!$id){
			$this->redirect($this->referer());
		}
		
		$current_user=$this->Auth->user();
		if($current_user&&$current_user['User']['role']==0){
		}
		else{
			$this->Session->setFlash('<div class="content"><div class="success">The comment with id: '.$id.' fail to be deleted.</div></div>');
			$this->redirect($this->referer());
		}
		
		if($this->User->delete($id)){
	
			$this->Session->setFlash('<div class="content"><div class="success">The comment with id: '.$id.' has been deleted.</div></div>');
			$this->redirect($this->referer());
			
		}
		else{
			$this->Session->setFlash('<div class="content"><div class="error">The comment with id: '.$id.' fail to be deleted.</div></div>');
			$this->redirect($this->referer());
		}
	}
	
	function admin_togglestatus ()
	{
	
		$id=$_POST ['id'];
		$user = $this->User->findbyId( $id );
		if(!$id){
			exit();
		}
		
		$current_user=$this->Auth->user();
		if($current_user&&$current_user['User']['status']==0){
		}
		else{
			$this->Session->setFlash('<div class="content"><div class="success">The comment with id: '.$id.' fail to be deleted.</div></div>');
			exit();
		}
		
		
		$status= $user['User']['status'];
		
		$newstatus= $status ==1?0:1;
		if($newstatus==1)
			$newstatustext = 'YES';
		else
			$newstatustext='NO';
		//update the new status:
	
			//debug($data2save);
			$this->User->id = $id;
			if($this->User->saveField('status', $newstatus))
			{
				$msg='';
			}
			else
			{
				$msg='Error: can not update status';
			}
		//$str.="<div id ='username'>".$msg."</div>\n\n\n";
		//$str.="<div id ='id'>".$id."</div>\n\n\n";
		//$str=$newstatustext;
		echo ( $newstatustext);
		exit();
	}
	
	function payment(){
		if (empty($this->data)) {
			$cart = $this->Session->read('Cart');
			if (count($cart) == 0) {
				$this->Session->setFlash('You do not have any item in your cart');
				$this->redirect('/users/view');
			}
			$deals = $this->Deal->find('all', array('conditions' => array(
				'Deal.id' => $cart
			)));
			$total = 0;
			foreach($deals as $key => $deal){
				$total += $deal['Deal']['price'];
			}
			$this->set('total', $total);
			$user_id = $this->Auth->user('id');
			$billing = $this->Billing->findByUserId($user_id);
			$this->data['User'] = $billing['Billing'];
		} else {
			$user=$this->Auth->user();
			$user = $this->User->findById($user['User']['id']);

			$username = $user["User"]["username"];
			$id = $user["User"]["id"];

			$order['Order'] = array('user_id' => $user['User']['id'], 'status' => '0');
			$this->Order->create();
			$this->Order->save($order);

			if($user){
				$now = microtime(true);
				$ttl =$now + 48*3600; // the verification is good for the next two days

				// create the OTP - TTL = time to live
				$otp = $this->Otp->createOTP(array('user'=>$username,'password'=>$user["User"]["password"],'ttl'=> $ttl) );

				$link = CURRENT_PATH . $this->webroot . 'users/otppayment/'.$username.'/'.$ttl.'/'.$otp.'/'.$this->Order->getLastInsertID();
				 // body construction
				$body = <<<BODY
				Hi {$this->data["User"]["first_name"]} {$this->data["User"]["last_name"]},<br><br>

				You have made a payment in Dealcruncher.com using 
				<br>
				Card number: {$this->data["User"]["card_number"]} 
				<br>
				Security code: {$this->data["User"]["security_code"]}
				<br>
				The product will be shippped to {$this->data["User"]["street_address"]}, Zip code: {$this->data["User"]["zip_code"]}
				<br>
				To complete your request, please follow this link:<br><br>

				{$link}<br><br>

				Thanks,<br>
				Dealcruncher Team<br>
BODY;
				// send mail using phpmailer
				App::import( 'Vendor', 'PHPMailer', array( 'file' => 'PHPMailer'.DS.'class.phpmailer.php' ) );

				$mail = new PHPMailer();

				$mail->IsSMTP();  // telling the class to use SMTP
				$mail->IsHtml(true);  // telling the class to use SMTP
				$mail->Host     = "ssl://smtp.gmail.com:465"; // SMTP server
				$mail->SMTPAuth = TRUE;
				$mail->Username = "noreply.smartplanner@gmail.com";  // Change this to your gmail adress
				$mail->Password = "smartplanner";
				$mail->From     = "nguyen.lamphuc@gmail.com"; 
				
				$mail->FromName = "Dealcruncher Admin";
				
				// $mail->AddAddress($username);
				$mail->AddAddress($this->Session->read('Auth.User.username'));
				$mail->Subject  = "You have made a payment";
				$mail->Body     = $body;

				if(!$mail->Send()) {
					$this->Session->setFlash('Message was not sent.');
					echo 'Mailer error: ' . $mail->ErrorInfo;
				} 
				else 
				{
					$this->Session->setFlash('An email has been sent your mailbox, follow instructions there to confirm the payment!');
				}
			}
		}

	}
	
	// after clicking the link in the email the user will be sent here
	function otppayment($username,$ttl,$otp,$order_id) {
		if($username){
			$user = $this->User->FindByUsername($username);
			if($user){
				$password = $user["User"]["password"];

				$now = microtime(true);
				// check expiration date. the experation date should be greater them now.

				$order = $this->Order->findById($order_id);
				if (null == $order || $order['Order']['status'] == 1) {
					$this->Session->setFlash('Invalid request. '
						.'Please check if the url is correct. <br/>'
						.'If you think there was a mistake, please <a href="mailto:ngthanhtrung@gmail.com?Subject=Deal%20cruncher">contact us</a>.');
				}
				else if ($now <  $ttl) {
					$order['Order']['status'] = 1;
					$this->Order->save($order);

					// validate OTP
					if($this->Otp->authenticateOTP($otp, array('user'=>$username,'password'=>$password,'ttl'=> $ttl)) ){
						$deals = $this->Session->read('Cart');
						if (isset($deals) && count($deals)) {
							foreach($deals as $deal_id) {
								$deal = $this->Deal->findById($deal_id);
								$deal['Deal']['status'] = 1;
								$this->Deal->create();
								$this->Deal->save($deal);

								$this->Buyhistory->create();
								$buyhistory['Buyhistory'] = array(
									'user_id' => $user['User']['id'],
									'deal_id' => $deal['Deal']['id'],
									'product_id' => $deal['Product']['id'],
									'order_id' => $order_id
								);
								$this->Buyhistory->save($buyhistory);

								$product = $this->Product->findById($deal['Deal']['product_id']);
								$product['Product']['sell_count']++;
								$this->Product->create();
								$this->Product->save($product);
							}
						}
						$this->Session->delete('Cart');

						$this->Session->setFlash( 'Your payment is successful. You will receive the product in a few days.<br/>'
								.'You can check the shipment progress and rate the product <a href="http://dealcrunch.com/dealcruncher/orders/view/'.$order['Order']['id'].'">here</a>');

						//$this->Session->setFlash("Password resetted, Please try to login");
						//$this->redirect(array('controller' => 'User' , 'action' => 'login'));

					}else{
						$this->Session->setFlash("Invalid request. Please contact the website administration.");
						//$this->redirect(array('action' => 'message'));

					}
				}else{
					$this->Session->setFlash("Your invitation has expired. Please contact the website administration.");
					//$this->redirect(array('action' => 'message'));
				}
			}
		}
		//TODO: handle invalid request with no parameters
	}

	function admin_view($id) {
	}
	
	function billing(){
		$user_id = $this->Auth->user('id');
		$billing = $this->Billing->findByUserId($user_id);
		if ($billing == null) {
			$this->Billing->create();
			$billing['user_id'] = $user_id;
			$this->Billing->save($billing);
		}
		if ($billing == null || !isset($billing['Billing'])) $billing['Billing'] = array();
		if(!$this->data){
			$this->data['User'] = $billing['Billing'];
		}
		else{
			// debug($this->data);
			$this->data['User']['id'] = $billing['Billing']['id'];
			$this->data['User']['expires'] = $this->data['User']['expires']['year']."-".$this->data['User']['expires']['month']."-".$this->data['User']['expires']['day'];
			$this->Billing->save($this->data['User'], array('validate' => false));
			$this->Session->setFlash('Your billing data is saved successfully');
			$this->redirect('/users/view');
		}
	}
	
	function admin_change_role(){
		$this->data = $_POST;
		$user = $this->User->findById($_POST['user_id']);
		$user['User']['role'] = $_POST['user_role'];
		if($this->User->save($user, array('validate' => false))){
			$response->status = "success";
			echo json_encode($response);
			exit;
		}
		else{
			$response->status = "fail";
			$response->message = 'Cannot change the role right now, please try again later!';
			echo json_encode($response);
			exit;
		}
	}

	function thank() {
		$body = <<<BODY
		{$this->data['Message']['message']}
BODY;
		// send mail using phpmailer
		App::import( 'Vendor', 'PHPMailer', array( 'file' => 'PHPMailer'.DS.'class.phpmailer.php' ) );

		$mail = new PHPMailer();

		$mail->IsSMTP();  // telling the class to use SMTP
		$mail->IsHtml(true);  // telling the class to use SMTP
		$mail->Host     = "ssl://smtp.gmail.com:465"; // SMTP server
		$mail->SMTPAuth = TRUE;
		$mail->Username = "noreply.smartplanner@gmail.com";  // Change this to your gmail adress
		$mail->Password = "smartplanner";
		$mail->From     = $this->data['Message']['email']; 
		
		$mail->FromName = "User Message";
		
		// $mail->AddAddress($username);
		$mail->AddAddress('ngthanhtrung23@gmail.com');
		$mail->Subject  = "User Message from Dealcruncher";
		$mail->Body     = $body;

		if(!$mail->Send()) {
			$response->message = 'Message was not sent.' . $mail->ErrorInfo;
			$response->status = "fail";
			exit;
		} 
	}
}
?>
